#!/usr/bin/python
# -*- coding: UTF-8 -*-

"""
@author: jiu
@contact: 643562684@qq.com
@time: 2022/3/10 14:35
"""
import csv
from common.log import logger
from common.base_read_file import BASE_FILE


class Read_CSV(BASE_FILE):
    def __init__(self, csv_file: str = '', _title_flag: bool = True, writes_flsh: bool = False):
        super(Read_CSV, self).__init__(csv_file)
        self._title_flag = _title_flag
        self._data = []
        self.writes_flsh = writes_flsh

    @property
    def data(self):
        if not self._data:
            with open(self._file, 'r', encoding='utf-8') as fp:
                file_path = [i for i in csv.reader(fp)]
                if self._title_flag:
                    #  Return in header format
                    title = file_path[0]
                    for i in file_path[1:]:
                        self._data.append(dict(zip(title, i)))

                    return self._data
                else:
                    # Return without header format
                    for i in file_path:
                        self._data.append(i)

                    return self._data
        return self._data

    def write_data(self, data=None, write_format: str = 'w'):
        """

        :param data: wirte  data
        :param write_format: Format of file writing
        :param writes_flsh: Inhale multiple lines at one time [[],[],[]] = True
        :return:
        """
        # 写入头信息
        with open(self._file, mode=write_format, encoding='utf-8', newline='\n') as fp:
            if not data:
                logger.error("CSV file write information is empty ！！")
                raise ValueError
            write_obj = csv.writer(fp)

            if self.writes_flsh:
                if isinstance(data[0], dict):
                    _title = data[0].keys()
                    write_obj.writerow(_title)
                    self.writes_flsh = False

                    for i in data:
                        write_obj.writerow(i.values())
                else:
                    for i in data:
                        write_obj.writerow(i)




